/**!
 * @Author: zx·H
 * @Date: 2018-07-19 11:24:21
 * @LastEditors: zx·H
 * @LastEditTime: 2018-07-19 11:26:55
 * @Description: gulp 配置，有两个问题
 * 1、改完名后，html的名字不会跟着改变
 * 2、打开浏览器自动更新时，不能用module
 */

var gulp = require("gulp"),  
    rename = require("gulp-rename"),
    watch = require("gulp-watch");

//编译报错控制
var notify = require('gulp-notify'),
    plumber = require('gulp-plumber');

//js es6编译以及压缩文件
var babel = require("gulp-babel"),
    uglify = require('gulp-uglify');

//css 压缩文件
var csso = require('gulp-csso'),
    uncss = require('gulp-uncss'),
    autoprefixer = require('gulp-autoprefixer');

//热重载
var browserSync = require('browser-sync'),
    reload = browserSync.reload; 


/**
 * 如果要想保留错误信息
 * plumber({errorHandler: notify.onError('Error: <%= error.message %>')})
 * @ notify.onError() 需安装 'gulp-notify'插件
 */
gulp.task("scripts", function () {  
    return gulp.src("src/js/**/*.js") 
    .pipe(plumber())  
    .pipe(babel())
    .pipe(uglify())
    //.pipe(rename({suffix: '.min'}))  
    .pipe(gulp.dest("dist/js"))
    .pipe(reload({ stream: true }));  
});

gulp.task("mincss",function() {
    return gulp.src("src/css/**/*.css") 
    .pipe(plumber())
    .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))  
    .pipe(uncss({
        html: ["src/index.html","src/view/**/*.html"]
    }))
    .pipe(csso())
    //.pipe(rename({suffix: '.min'}))  
    .pipe(gulp.dest("dist/css"))
    .pipe(reload({ stream: true }));
})

gulp.task("copy",function() {
    gulp.src("src/index.html")
        .pipe(gulp.dest("dist/")).reload;

    gulp.src("src/view/**/*.html")
        .pipe(gulp.dest("dist/view")).reload;

    gulp.src("src/image/**/*") 
        .pipe(gulp.dest("dist/image"));
})

gulp.task('server',function() {
    browserSync.init({
        files:['**'],
        server: {
            baseDir: "./dist",
            index: 'index.html'
        },
        port:8050
    });
    gulp.watch('src/js/**/*.js',['scripts']);
    gulp.watch('src/css/**/*.css',['mincss']);
    gulp.watch("src/index.html",['copy']);
    gulp.watch('src/view/**/*.html',['copy']);
    gulp.watch('src/image/**/*',['copy']);
});

gulp.task('default',['scripts','mincss','copy','server']);